import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import styled from 'styled-components';
import Segment, { SegmentItemType } from './Segment';
import List from './List';
import { RankInfo, RankType, ranking } from '../../service';
import NotificationCenter from '../../utils/notification';
import { NotificationTimeKey, NotificationTimeName } from './constants';
import Loading from '../../component/Loading';

const SegmentBox = styled(Segment)`
    margin-top: 1.875rem;
    flex: 1;
    overflow: visible;
    min-height: 0;
`


const Rank: React.FC = () => {
    const { t } = useTranslation()
    const [data, setData] = useState<RankInfo>()
    const segments = useMemo(() => {
        return [
            // { label: t('ranking.segment.inviteDaily'), key: RankType.InviteDaily },
            { label: t('ranking.segment.invite'), key: RankType.Invite },
            // { label: t('ranking.segment.level'), key: RankType.Detector },
        ]
    }, [t])
    const defaultInfo = useMemo(() => segments[0], [segments])
    const [type, setType] = useState<RankType>(defaultInfo.key)
    const [loading, setLoading] = useState(false);

    const handleClick = useCallback(async (item: SegmentItemType) => {
        const rankType = item.key as RankType
        setType(rankType)
        setData({
            snapTime: '',
            items: []
        })
        setLoading(true)
        const result = await ranking({ type: rankType })
        setLoading(false)
        if (!result.success) {
            return
        }

        setData(result.data)
        NotificationCenter.post(NotificationTimeName, { [NotificationTimeKey]: result.data?.snapTime })

    }, [])

    useEffect(() => {
        handleClick(defaultInfo)
    }, [handleClick, defaultInfo])

    return <>
        <SegmentBox
            segments={segments}
            onClick={handleClick}
        >
            <List
                data={data}
                type={type}
            />
        </SegmentBox>
        <Loading show={loading} />
    </>
}

export default Rank;